<?php

namespace app\admin\controller\life;

use app\common\controller\Backend;

use think\Controller;
use think\Request;
use think\Db;
use think\Url;

/**
 * @icon fa fa-circle-o
 */
class Life extends Backend
{
    /**
     * Type模型对象
     */
    protected $model = null;
    
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Type');
    }
    /*查看*/
    public function index(){
        $typeModel = model('Type');
        $kinds = $typeModel::$life_kind;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('pkey_name')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $where = array();
            $where['category'] = array('eq', 2);
            $where['is_delete'] = array('eq', 0);
            $where['p_id'] = array('eq', 28);
            
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
            
            $list = $this->model
                ->field('type_id, type_name, kind, category, is_delete')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            
            foreach($list as &$v) {
                $v['is_delete'] = $v['is_delete']==0?'显示':'不显示';
                $v['kind'] = $kinds[$v['kind']];
            }
            unset($v);
            
            $result = array("total" => $total, "rows" => $list);
            
            return json($result);
        }
        
        //设置列表工具栏
        $btns = array('refresh', 'add');
        
        $kinds = json_encode($kinds, JSON_UNESCAPED_UNICODE);
        $this->view->assign('kinds', $kinds);
        $this->view->assign('btns', $btns);
        return $this->view->fetch();
    }
    /*添加*/
    public function add(){
        $typeModel = model('Type');
        $kinds = $typeModel::$life_kind;
        if ($this->request->isPost()) {
            $kind = input('kind');
            $exist = $this->model->where(array('kind' => $kind))->find();
            if($exist) {
                $this->error('该类型已存在');
                exit;
            }
            
            if(empty($kind)){
                $this->error("不能提交空信息");
            }
            $type_name = $kinds[$kind];
            $add_data = array(
                'type_name' => $type_name,
                'kind' => $kind,
                'category' => 2,
                'type_tpl' => '0',
                'click_pay' => 0,
                'see_pay' => 0,
                'cash_deposit' => 0,
                'offer_reward' => 0
            );
            
            // 插入单个记录
            $re = $this->model->insert($add_data);
            if($re) {
                $this->success("添加成功");
            } else {
                $this->error("添加失败");
            }
        } else {
            $this->view->assign('option_count', 0);
            $this->view->assign('option_list', array());
        }
        //设置列表工具栏
        $btns = array('refresh', 'add');
        $this->view->assign('btns', $btns);
        $this->view->assign('kinds', $kinds);
        return $this->view->fetch();
    }
    /*编辑*/
    public function edit($ids = NULL){
        $type_id = $ids;
        $type_info = Db::name('type')->where(array("is_delete" => 0,"type_id" => $type_id))->find();
        
        $option_list = Db::name('option')->where(array("is_delete" => 0,"type_id" => $type_id))->order("num ASC,option_id ASC")->select();
        
        foreach($option_list as  $key=>$val){
            $data_list = Db('option_list')->where(array("option_id" => $val['option_id']))->column("list_name");
            if(!empty($data_list)){
                $option_list[$key]['data_list'] = implode("|",$data_list);
            }
        }
        $option_count = Db::name('option')->where(array("type_id"=>$type_id))->max("num");
        $option_count = $option_count ? $option_count : 0;
        
        $this->view->assign("option_count",$option_count);
        $this->view->assign("type_info",$type_info);
        $this->view->assign("option_list",$option_list);
        
        if ($this->request->isPost()) {
            $type_name = input('type_name');
            $type_tpl = input('type_tpl');
            $kind = input('kind');
            $click_pay = input('click_pay');
            $see_pay = input('see_pay');
            $cash_deposit = input('cash_deposit');
            $offer_reward = input('offer_reward');
            if(empty($type_name)){
                $this->error("信息分类名称不能为空");
            }
            if($type_id){
                $save_data = array(
                    'type_name' => $type_name,
                    'type_tpl' => $type_tpl,
                    'kind' => $kind,
                    'click_pay' => $click_pay,
                    'see_pay' => $see_pay,
                    'cash_deposit' => $cash_deposit,
                    'offer_reward' => $offer_reward
                );
                Db::name('type')->where(array("is_delete" => 0,"type_id" => $type_id))->update($save_data);
            }
            
            if(empty($type_id)){
                $this->error("添加失败");
            }
            
            $inputData = input();
            $type_num = $inputData['type_num'];
            $option_name = $inputData['option_name'];
            $option_type = $inputData['option_type'];
            $data_list = $inputData['data_list'];
            $is_show_name = $inputData['is_show_name'];
            $is_must = $inputData['is_must'];
            $option_holder = $inputData['option_holder'];
            $option_notes = $inputData['option_notes'];
            $is_self = $inputData['is_self'];
            $self_suffix = $inputData['self_suffix'];
            $option_id_arr = $inputData['option_id'];
            
            $OptionModel = Db::name('option');
            
            $error = "";
            
            foreach($type_num as $k=>$v){
                $a = $k+1;
                if(empty($option_name[$k])){
                    $error = "请选填写信息【".$a."】的名称";
                    break;
                }
                if(empty($option_type[$k]) && $option_type[$k] != "0"){
                    $error = "请选择信息【".$a."】的类型";
                    break;
                }
                if(in_array($option_type[$k],array(2,3)) && empty($data_list[$k])){
                    $error = "请填写信息【".$a."】的选项";
                    break;
                }
            }
            if(!empty($error)){
                $this->error($error);
            }
            
            $ListModel = Db::name('option_list');
            foreach($type_num as $key=>$num){
                $data = array();
                $data['type_id'] = $type_id;
                $data['num'] = $num;
                $data['option_name'] = $option_name[$key];
                $data['option_type'] = $option_type[$key];
                
                $data['is_show_name'] = $is_show_name[$key] ? $is_show_name[$key] : 1;
                $data['is_must'] = $is_must[$key] ? $is_must[$key] : 0;
                $data['option_holder'] = $option_holder[$key] ? $option_holder[$key] : '';
                $data['option_notes'] = $option_notes[$key] ? $option_notes[$key] : "";
                $data['is_self'] = $is_self[$key] ?  $is_self[$key] : 0;
                $data['self_suffix'] = $self_suffix[$key] ? $self_suffix[$key] : "";
                
                if(empty($option_id_arr[$key])){
                    $OptionModel->insert($data);
                    $data['option_id'] = Db::getLastInsID();
                } else {
                    $data['option_id'] = $option_id_arr[$key];
                    $OptionModel->update($data);
                    $ListModel->where('option_id', $data['option_id'])->delete();
                }
                
                if(in_array($data['option_type'],array(2,3))){
                    $list_array = explode("|",$data_list[$key]);
                    $option_list = array();
                    foreach($list_array as $name){
                        $option_list[] = array("option_id"=>$data['option_id'],"list_name"=>$name);
                    }
                    $ListModel->insertAll($option_list);
                }
            }
            
            if(isset($inputData['del_option'])) {
                $option_del = $inputData['del_option'];
                if(!empty($option_del) && is_array($option_del)){
                    $OptionModel->where('option_id', 'in', $option_del)->update(['is_delete' => 1]);
                }
            }
            
            $this->success("操作成功");
        }
        
        return $this->view->fetch();
    }
    /*删除*/
    public function del($ids = ""){
        $type_id = $ids;
        $status = Db::name('type')->where(array("type_id" => $type_id))->update(array("is_delete"=>1));
        if($status){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }
    /*餐饮生活信息列表*/
    public function amoy_list() {
        $this->model = model('Amoy');
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('pkey_name')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        
            $where = array();
            $where['t.category'] = array('eq', 2);
            $where['t.p_id'] = array('eq', 28);
            $where['a.is_show'] = array('eq', 1);
            $inputData = input();
            $filter = json_decode($inputData['filter'], true);
            if(!empty($filter['type_name'])) {
                $where['t.type_id'] = array('eq', $filter['type_name']);
            }
            if(!empty($filter['role'])) {
                $where['a.role'] = array('eq', $filter['role']);
            }
            if(!empty($filter['add_time'])) {
                $date = explode(',', $filter['add_time']);
                foreach($date as &$v){
                    $v = strtotime($v);
                }
                $where['a.add_time'] = array('between', $date);
            }
        
            $total = $this->model
                ->alias('a')
                ->join('cy_type t ', 'a.type_id = t.type_id')
                ->where($where)
                ->order('a.amoy_id DESC')
                ->count();
            $fields = "t.type_name AS type_name, a.amoy_id, a.user_id, a.type_id, a.auto_content, a.free_content, a.add_time, a.up_time, a.is_show, a.title, a.is_push";
            $list = $this->model
                ->alias('a')
                ->join('cy_type t ', 'a.type_id = t.type_id')
                ->field($fields)
                ->where($where)
                ->order('a.amoy_id DESC')
                ->limit($offset, $limit)
                ->select();
            
            foreach($list as &$v) {
                $v['add_time'] = date('Y/m/d H:i', $v['add_time']);
                $v['is_show'] = $v['is_show']==1?'显示':'不显示';
                $v['is_push'] = $v['is_push']==1?'推送':'不推送';
                $v['content'] = mb_substr(strip_tags($v['auto_content']), 0, 80) . '...';
                $v['title'] = $v['title']?$v['title']:'';
            }
            unset($v);
        
            $result = array("total" => $total, "rows" => $list);
        
            return json($result);
        }
    
        //设置列表工具栏
        $btns = array('refresh', 'add');
        $this->view->assign('btns', $btns);
    
        //查询信息分类
        $typeModel = model('Type');
        $types = $typeModel->getType(null, 28);
        $types = json_encode($types, JSON_UNESCAPED_UNICODE);
        $this->view->assign('types', $types);
    
        return $this->view->fetch();
    }
    //添加餐饮圈信息
    public function amoy_add(){
        $typeModel = model('Type');
        $kinds = $typeModel->getType(null, 28);
        unset($kinds[20]); //去除掉论坛分类,论坛不能在后台添加
        
        if ($this->request->isPost()) {
            $inputData = input();
            $title = $inputData['title'];
            $source = isset($inputData['source'])?$inputData['source']:0;
            $type_id = $inputData['type_id'];
            $list_show = $inputData['list_show'];
            $is_top = isset($inputData['is_top'])?time():0;
            $is_hot = isset($inputData['is_hot'])?1:0;
            $is_hot_search = isset($inputData['is_hot_search'])?1:0;
            $is_push = isset($inputData['is_push'])?1:0;
            $cover = $inputData['cover'];
            $cover = str_replace("\\", "/", $cover);
            $auto_content = $inputData['auto_content'];
            $auto_content = preg_replace('/(<embed.+src=\"?.+)(\/assets)(.+\.(mp4|avi|rmvb)\"?.+>)/i',"\${1}http://admin.moments.taoxiansheng.com/assets/\${3}",$auto_content);

            $add_data = array(
                'user_id' => 1,
                'source' => $source,
                'title' => $title,
                'type_id' => $type_id,
                'list_show' => $list_show,
                'is_top' => $is_top,
                'is_hot' => $is_hot,
                'is_hot_search' => $is_hot_search,
                'is_push' => $is_push,
                'is_show' => 1,
                'cover' => $cover,
                'auto_content' => $auto_content,
                'add_time' => time()
            );
            // 插入单个记录
            $re = Db::name('amoy')->insert($add_data);
            if($re) {
                $this->success("添加成功");
            } else {
                $this->error("添加失败");
            }
        } else {
            $this->view->assign('option_count', 0);
            $this->view->assign('option_list', array());
        }
        
        $this->view->assign('kinds', $kinds);
        $this->view->assign('uploader_url', Url::build('admin/life/life/upload_picture',array('session_id'=>session_id())));
        return $this->view->fetch();
    }
    //修改餐饮圈信息
    public function amoy_edit($ids = NULL){
        $amoy_id = $ids;
        $typeModel = model('Type');
        $kinds = $typeModel->getType(null, 28);
        
        $amoyModel = model('Amoy');
        $row = Db::name('amoy')->where(array('amoy_id' => $amoy_id))->find();
        $cover = explode(',', $row['cover']);
        
        if($this->request->isPost()) {
            $inputData = input();
            $title = $inputData['title'];
            $source = isset($inputData['source'])?$inputData['source']:0;
            $type_id = $inputData['type_id'];
            $list_show = $inputData['list_show'];
            $is_top = isset($inputData['is_top'])?time():0;
            $is_hot = isset($inputData['is_hot'])?1:0;
            $is_hot_search = isset($inputData['is_hot_search'])?1:0;
            $is_push = isset($inputData['is_push'])?1:0;
            $cover = $inputData['cover'];
            $cover = str_replace("\\", "/", $cover);
            $auto_content = $inputData['auto_content'];
            $auto_content = preg_replace('/(<embed.+src=\"?)(\/assets\/)(.+\.(mp4|avi|rmvb)\"?.+>)/i',"\${1}http://admin.moments.taoxiansheng.com/assets/\${3}",$auto_content);
            $save_data = array(
                'title' => $title,
                'source' => $source,
                'type_id' => $type_id,
                'list_show' => $list_show,
                'is_top' => $is_top,
                'is_hot' => $is_hot,
                'is_hot_search' => $is_hot_search,
                'is_push' => $is_push,
                'cover' => $cover,
                'auto_content' => $auto_content,
                'add_time' => time()
            );
            // 插入单个记录
            $re = $amoyModel->where(array('amoy_id' => $amoy_id))->update($save_data);
            if($re){
                $this->success("更改成功");
            } else {
                $this->error("更改失败");
            }
        }
        
        $this->view->assign('kinds', $kinds);
        $this->view->assign('row', $row);
        
        $this->view->assign('cover', $cover);
        return $this->view->fetch();
    }
    /*删除文章*/
    public function amoy_del($ids = ""){
        $amoy_id = $ids;
        $status = Db::name('amoy')->where(array("amoy_id" => $amoy_id))->update(array("is_show" => 0));
        if($status){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }
    
    public function upload_picture(Request $request) {
        // 获取表单上传文件
        $file = $request->file('file');
        if (empty($file)) {
            $this->error('请选择上传文件');
        }

        // 移动到框架应用根目录/public_html/uploads/ 目录下
        $info = $file->move(ROOT_PATH . 'public_html' . DS . 'uploads');
        $url= DS . "uploads" . DS .$info->getRealPath();
        $name = DS . "uploads" . DS . $info->getSaveName();
        $return['url'] = $url;
        $return['name'] = $name;

        return json($return);
    }
}
